﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FAQFrameworks
{
    public class ValidateList
    {
        List<ValidateHandler> validateList;

        public void AddValidate(ValidateHandler handler)
        {
            validateList.Add(handler);
        }

        internal object obj;

        public ValidateList(object obj)
            : this()
        {
            this.obj = obj;
        }

        public ValidateList()
        {
            list = new List<string>();
            validateList = new List<ValidateHandler>();
            e = new ValidateEventArgs(this);

        }

        ValidateEventArgs e;

        public virtual void OnValidate()
        {
            foreach (ValidateHandler handler in validateList)
            {
                e.Continue = true;
                handler(obj, e);
                if (!e.IsValid)
                {
                    if (isValid)
                    {
                        this.isValid = false;
                    }
                    if (!e.Continue)
                    {
                        break;
                    }
                }
            }
        }

        bool isValid = true;

        public bool IsValid
        {
            get
            {
                OnValidate();
                return isValid;
            }
        }

        public string[] Message
        {
            get
            {
                return list.ToArray();
            }
        }

        internal List<string> list;
    }

    public delegate void ValidateHandler
           (object sender, ValidateEventArgs e);

    public class ValidateEventArgs : EventArgs
    {
        public ValidateEventArgs(ValidateList validates)
        {
            this.validates = validates;
            this.IsValid = true;
        }

        ValidateList validates;

        public object Value
        {
            get
            {
                return validates.obj;
            }
        }

        public bool IsValid { get; set; }

        public bool Continue { get; set; }

        string messsge;

        public string Messsge
        {
            get { return messsge; }
            set
            {
                messsge = value;
                if (!string.IsNullOrEmpty(value))
                {
                    validates.list.Add(value);
                }
            }
        }
    }
}